<?php
namespace Client\Common;

define("TOKEN", "RD4KoqqrGgGCJTuK");
class WechatHelper
{
    /**
     * 是否是微信平台
     * @return boolean
     */
    public function isWechatPlatform(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        
        }else {
            return false;
        
        }
    }
    
    /**
     * 是否是微信平台
     * @return boolean
     */
    public static function isWxPlatform(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
    
        }else {
            return false;
    
        }
    }
    
    public function getDeviceType(){ 
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']); 
        $type = 'other'; 
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {  
            $type = 'ios'; 
        } 
        if(strpos($agent, 'android'))
        {  
            $type = 'android'; 
        } 
        return $type;
    }
    
    /**
     * 获取微信unionid  openid
     */
    public function getWechatInfo($data_array){
        
        $app_id = $data_array['app_id'];
        $app_secret = $data_array['app_secret'];
        $code = $data_array['code'];
        $url ='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app_id.'&secret='.$app_secret.'&code='.$code.'&grant_type=authorization_code';
        $output = $this->httpRquest($url);
        return json_decode($output, true);
    }
    
    public function getWechatUserInfo($data_array){
    
        $open_id = $data_array['open_id'];
        $access_token = $data_array['access_token'];
        $url ='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$open_id.'&lang=zh_CN';
        $output = $this->httpRquest($url);
        return json_decode($output, true);
    }
    
    /**
     * 
     * @param unknown $url
     * @param unknown $data
     * @return mixed
     */
    public function httpRquest($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
    
        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    
        $res = curl_exec($curl);
        if(curl_errno($curl)){
            return 'Errno'.curl_error($curl);
        }
        curl_close($curl);
        
        return $res;
    }
    
    /**
     * wechat API
     * @param unknown $echoStr
     * @param unknown $data
     * @return unknown
     */
    public function valid($echoStr,$data){
        //valid signature , option
        if($this->checkSignature($data)){
            return $echoStr;
            exit;
        }
    }
    
    private function checkSignature($data){
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new \Exception('TOKEN is not defined!');
        }
           
        $signature = $data['signature'];
        $timestamp = $data['timestamp'];
        $nonce = $data['nonce'];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
    
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    

    /**
     * 
     * @return unknown
     */
    function getAccessToken($appid, $app_secret){
        $file_dir = str_replace(substr($_SERVER['DOCUMENT_ROOT'],-6) , '', $_SERVER['DOCUMENT_ROOT']);
   
        $data = json_decode(file_get_contents($file_dir."config/wechat/access_token.json"));
        
        if($data->expire_time < time())
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$app_secret;
            $res = json_decode($this->httpRquest($url));
            $access_token = $res->access_token;
            if($access_token)
            {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen($file_dir."config/wechat/access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }else{
            $access_token = $data->access_token;
        }
    
        return $access_token;
    }
    
    public function getSignPackage($app_id, $app_secret){
        
        $jsapiTicket = $this->getJsApiTicket($app_id, $app_secret);
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $app_id,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }
    
    //获取微信服务器IP地址
    public function getWechatServerIp($appid, $app_secret){
        $accessToken = $this->getAccessToken($appid, $app_secret);
        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=$accessToken";
        return $res = json_decode($this->httpRquest($url));
    }
    
    //用户分析数据接口
    
    
    private function getJsApiTicket($appid, $app_secret){
        $file_dir = str_replace(substr($_SERVER['DOCUMENT_ROOT'],-6) , '', $_SERVER['DOCUMENT_ROOT']);
        $data = json_decode(file_get_contents($file_dir."config/wechat/jsapi_ticket.json"));
        
        if($data->expire_time < time())
        {
            $accessToken = $this->getAccessToken($appid, $app_secret);
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpRquest($url));
            $ticket = $res->ticket;
            if($ticket)
            {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen($file_dir."config/wechat/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }else{
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }
    
    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i< $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
   
}